<?php
class CarApp extends CommonApp {
   
    public function indexAct(){
        $this->checklogin();
        $member = My::arr2var($_SESSION,'member');
        $result = DB('car')->where("member_id = '{$member['id']}'")->select();//对应用户id的商品
        $this->assign('result',$result);
		$this->display();
    }

    //添加购物车
    public function addToCartAct(){
    	if(!My::is_id(My::arr2var($_REQUEST,'goodsid')))
    		$this->ajaxReturn(300,'商品id参数有误');
    	if(!isset($_SESSION['member']))
 			$this->ajaxReturn(201,'请先登陆!');
        if($_POST)
            $data = array(
                'price' => $_POST['price_real'],//价格
                'goodsname' => $_POST['goodsname'],//标题
                'partake' => $_POST['partake'],//剩余人数
                'image' => $_POST['image'],//图片
                'rate' => $_POST['rate'],
                );
        else if($_GET){
            $result = DB('goods')->where("id = '{$_GET['goodsid']}'")->clear()->find();
            $data = array(
                'goodsname' => $result['title'],//标题
                'price' => $result['price'],
                'partake' => ($result['number']-$result['partake']),//剩余人数
                'image' => $result['image'],//图片
                'rate' => $result['rate'],//揭晓时间
                );
        }
        $data['member_id'] = $_SESSION['member']['id'];//用户id'
        $data['goods_id'] = $_REQUEST['goodsid'];//商品id
        $data['orderid'] = $this->createOrderNm();//订单号
        $data['adddate'] = date('Y-m-d H:i:s');
    	$check = DB('car')->where("goods_id = '{$data['goods_id']}' AND member_id = '{$data['member_id']}'")->clear()->find();
    	if($check>0)
    		$this->ajaxReturn(202,'已在购物车里，赶紧去清空吧！');
    	$add = DB('car')->clear()->add($data);
    	if($add>0){
            $count = DB('car')->where("member_id = '{$data['member_id']}'")->clear()->count();
            $this->ajaxReturn(200,$count);
        }
    	else $this->ajaxReturn(300,'购物车加入失败！');
    }
   
    //删除购物车
    public function deleteAct(){
        if($_GET['ids']){
            $ids = explode(',', $_GET['ids']);
            $str = '';
            foreach ($ids as $key => &$value) {
                if(My::is_id($value)){
                    $ok = DB('car')->where("id={$value}")->clear()->delete();
                    if($ok)
                        $str = ($key+1).'条购物车清除成功！';
                    else
                        $str .= '第'.($key+1).'条购物车清除失败！';
                }
            }
            $member_id = $_SESSION['member']['id'];//用户id'
            $count = DB('car')->where("member_id = '{$member_id}'")->clear()->count();
            $this->ajaxReturn(200,$count);
        }else $this->ajaxReturn(300,'id参数出错！');
        
    }
}